package com.glory.brepda.activity.recipe;

import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.TempRecipeListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.TempRecipeEntity;
import com.glory.brepda.entity.UpdateIPEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * FileName: TempRecipeActivity
 * Author: XJH
 * Date: 2021/4/9 10:34
 * Description:
 * History:
 */
public class TempRecipeActivity extends BaseActivity {
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etEqpID)
    FreeUI_ClearEditText etEqpID;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etChipName)
    FreeUI_ClearEditText etChipName;
    @BindView(R.id.etDBCode)
    FreeUI_ClearEditText etDBCode;
    @BindView(R.id.etPackageType)
    FreeUI_ClearEditText etPackageType;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.rvRecipeList)
    RecyclerView rvRecipeList;
    @BindView(R.id.tvDownLoad)
    TextView tvDownLoad;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvEqpWorkType)
    TextView tvEqpWorkType;
    @BindView(R.id.tvProgramType)
    TextView tvProgramType;
    @BindView(R.id.tvProcessName)
    TextView tvProcessName;
    @BindView(R.id.etWaferSize)
    FreeUI_ClearEditText etWaferSize;
    @BindView(R.id.etDieSize)
    FreeUI_ClearEditText etDieSize;
    @BindView(R.id.etWrieSpec)
    FreeUI_ClearEditText etWrieSpec;
    @BindView(R.id.rbSingle1)
    RadioButton rbSingle1;
    @BindView(R.id.rbSingle2)
    RadioButton rbSingle2;
    @BindView(R.id.rbSingle3)
    RadioButton rbSingle3;
    @BindView(R.id.rbSingle4)
    RadioButton rbSingle4;
    @BindView(R.id.llSingle)
    LinearLayout llSingle;
    @BindView(R.id.tvCHIPTHICKNESS)
    TextView tvCHIPTHICKNESS;
    @BindView(R.id.llCHIPTHICKNESS)
    LinearLayout llCHIPTHICKNESS;
    @BindView(R.id.tvImage)
    TextView tvImage;
    @BindView(R.id.flProgramSource)
    FrameLayout flProgramSource;
    @BindView(R.id.tvProgramSource)
    TextView tvProgramSource;
    @BindView(R.id.ivProgramSource)
    ImageView ivProgramSource;
    @BindView(R.id.etDIE1)
    FreeUI_ClearEditText etDIE1;
    @BindView(R.id.etDIE2)
    FreeUI_ClearEditText etDIE2;
    @BindView(R.id.etDIE3)
    FreeUI_ClearEditText etDIE3;
    @BindView(R.id.etDIE4)
    FreeUI_ClearEditText etDIE4;
    @BindView(R.id.etDIE5)
    FreeUI_ClearEditText etDIE5;
    @BindView(R.id.etDIE6)
    FreeUI_ClearEditText etDIE6;
    @BindView(R.id.etUpDesc)
    FreeUI_ClearEditText etUpDesc;
    @BindView(R.id.etCurChipName)
    FreeUI_ClearEditText etCurChipName;
    @BindView(R.id.WBShow)
    LinearLayout WBShow;

    String PROCESSNAME = "";
    String EQPID = "";
    private String single = "";
    private int mID = -1;
    private TempRecipeListAdapter mAdapter;
    private LotInfoEntity mLotInfoEntity = null;
    private String mRecipeType = "GOLD";
    private FreeUI_GeneralPop mProgramSourcePop;
    private ArrayList<String> mProgramSourceList = new ArrayList<String>() {{
        add("新建");
        add("FOLLEW");
        add("升版");
    }};



    @Override
    protected int getLayoutResId() {
        return R.layout.activity_recipe_temp;
    }

    @Override
    protected void initView() {
        setMainLayout(llMain);
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        tvBaseSubmit.setText("查询");
//        tvBaseSubmit.setVisibility(View.GONE);
        listTv1.setText("设备编号");
        listTv2.setText("Recipe名称");
        listTv3.setText("Recipe版本");
        listTv4.setText("程序类型");
        initRecyclerView(rvRecipeList, this);
        mAdapter = new TempRecipeListAdapter(null, (recipeName, id) -> {
            mID = id;
//            if (recipeName.contains("-")){
//                String[] split = recipeName.split("-");
//                etBDNum.setText("C-BD-" + split[0]);
//            }else {
//                etBDNum.setText("C-BD-" + recipeName);
//            }
//
//            requestBdNumInfo();
        });
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(true);
        rvRecipeList.setAdapter(mAdapter);
        initEdit(etEqpID, s -> {

            getWqpInfo(s);
//                FreeUI_EntityCallBack<BaseResponseBean<UpdateIPEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<UpdateIPEntity>>
//                        (new TypeToken<BaseResponseBean<UpdateIPEntity>>() {
//                        }.getType(), getSupportFragmentManager(), this) {
//
//                    @Override
//                    public void onSuccess(Response<BaseResponseBean<UpdateIPEntity>> response) {
//                        super.onSuccess(response);
//                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
//                            UpdateIPEntity body = response.body().getResponse().getBody();
//                            tvEqpWorkType.setText(body.getEQUIPMENTTYPE());
//                            tvProgramType.setText(body.getPROGRAMTYPE());
//                        }
//                    }
//
//                    @Override
//                    public void onError(Response<BaseResponseBean<UpdateIPEntity>> response) {
//                        super.onError(response);
//                        loadError(response.getException(), "GETEQPINFOBYEQPID");
//                    }
//                };
//                JsonObject map = new JsonObject();
//                map.addProperty("total",13);
//                map.addProperty("pageNo",1);
//                map.addProperty("pageSize",50);
//                map.addProperty("sort","createTime");
//                map.addProperty("order","descending");
//                map.addProperty("equipmentId",s);
//                map.addProperty("status",-1);
//                map.addProperty("procedure","WB");
//                NetUtils.requestPostNet("getRecipeByStatus","RMS/getRecipeByStatus",this,map,callBack);


        });

        initEdit(etLot, s -> LotUtils.searchLotInfo(TempRecipeActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
            @Override
            public void onSuccess(LotInfoEntity response) {
                mLotInfoEntity = response;
                etChipName.setText(response.getCHIPNAME());
                etDBCode.setText(response.getBD_CODE());
                etPackageType.setText(response.getPACKAGETYPE());
                etWaferSize.setText(response.getWAFERSIZE());
                etDieSize.setText(response.getDIESIZE());
                etWrieSpec.setText(response.getWIRESPEC());
                tvCHIPTHICKNESS.setText(response.getCHIPTHICKNESS());
                switch (response.getISSINGLE()){
                    case "单":
                        single = "单";
                        rbSingle1.setChecked(true);
                        break;
                    case "双":
                        single = "双";
                        rbSingle2.setChecked(true);
                        break;
                    case "四":
                        single = "四";
                        rbSingle3.setChecked(true);
                        break;
                    case "六":
                        single = "六";
                        rbSingle4.setChecked(true);
                        break;
                    case "":
                        single = "";
                        llSingle.setVisibility(View.GONE);
                        break;
                }
            }

            @Override
            public void onFail(Throwable t) {
                loadError(t, "LOTQUERY");
            }
        }));
    }

    private void getWqpInfo(String eqpID) {
        FreeUI_EntityCallBack<BaseResponseBean<UpdateIPEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<UpdateIPEntity>>
                (new TypeToken<BaseResponseBean<UpdateIPEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<UpdateIPEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    UpdateIPEntity body = response.body().getResponse().getBody();
                    tvEqpWorkType.setText(body.getEQUIPMENTTYPE());
                    tvProgramType.setText(body.getPROGRAMTYPE());
                    tvProcessName.setText(body.getPROCESSNAME());
                    if (body.getPROCESSNAME().equals("WB")){
                        WBShow.setVisibility(View.VISIBLE);
                    }else {
                        WBShow.setVisibility(View.GONE);
                        cleanWBShow();
                    }
                    PROCESSNAME = body.getPROCESSNAME();
                    EQPID = eqpID;
                    if (body.getPROCESSNAME().equals("DS")){
                        llCHIPTHICKNESS.setVisibility(View.VISIBLE);
                    }else {
                        llCHIPTHICKNESS.setVisibility(View.GONE);
                    }
                    if (!body.getPROCESSNAME().equals("WB")){
                        tvImage.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<UpdateIPEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "GetEquipment");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID", eqpID);
        NetUtils.requestPostNet("IF.GetEquipment", "GetEquipment", TempRecipeActivity.this, map, callBack);
    }

    @Override
    protected void initData() {
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @OnClick({R.id.rbGold, R.id.rbEQP, R.id.tvDownLoad,R.id.tvImage, R.id.tvBaseSubmit,R.id.rbSingle1,R.id.rbSingle2,R.id.rbSingle3,R.id.rbSingle4,R.id.flProgramSource})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rbGold:
                mRecipeType = "GOLD";
                break;
            case R.id.rbEQP:
                mRecipeType = "EQP";
                break;
            case R.id.tvImage:
                if (mID == -1) {
                    showToast("请选中Recipe", false);
                    return;
                }
                if (getText(etDBCode).equals("")){
                    showToast("请输入配线图号", false);
                    return;
                }
                AtomicReference<TempRecipeEntity.TempRecipeInfoEntity> deta = new AtomicReference<>();
                mAdapter.getData().forEach(adapterData ->{
                    if (mID == adapterData.getId()){
                        deta.set(adapterData);
                    }
                });
                Bundle bundle = new Bundle();
                bundle.putString("EQPID", deta.get().getEquipmentId());
                bundle.putString("RecipeName", deta.get().getRecipeName());
                bundle.putString("ID", deta.get().getId()+"");
                bundle.putString("BDCODE", getText(etDBCode));
                bundle.putString("TITLE", "查看图片");
                FreeApi_Utils.skipWithExtraIntent("", bundle,TempRecipeActivity.this, SolderJointUpImageActivity.class);

                break;
            case R.id.tvDownLoad:
                if (mID == -1) {
                    showToast("请选中Recipe", false);
                    return;
                }
                if ("".equals(tvProgramType.getText().toString())) {
                    showToast("当前程序类型为空", false);
                    return;
                }
                if ("".equals(tvProcessName.getText().toString())) {
                    showToast("当前工序为空", false);
                    return;
                }
                if ("WB".equals(tvProcessName.getText().toString())) {
                    if (getText(etDBCode).equals("")){
                        showToast("请输入配线图号", false);
                        return;
                    }
                    if (getText(etWrieSpec).equals("")){
                        showToast("请输入丝材规格", false);
                        return;
                    }

                }
                if ("DS".equals(tvProcessName.getText().toString())) {
                    if (getText(etChipName).equals("")){
                        showToast("请输入芯片名", false);
                        return;
                    }
                }
                if ("DB".equals(tvProcessName.getText().toString())) {
                    if (getText(etPackageType).equals("")){
                        showToast("请输入封装形式", false);
                        return;
                    }
                    if (getText(etChipName).equals("")){
                        showToast("请输入芯片名", false);
                        return;
                    }
                }
                if (llCHIPTHICKNESS.getVisibility() == View.VISIBLE){
                    if (tvCHIPTHICKNESS.getText().toString().equals("")){
                        showToast("芯片厚度为空，请联系管理员", false);
                        return;
                    }
                }
                if (tvProgramSource.getText().toString().equals("升版") && etUpDesc.getText().toString().isEmpty()){
                    showToast("程序来源是升版时升版描述必填！", false);
                    return;
                }

                showSubmitDialog(new onSubmitListener() {
                    @Override
                    public void setOnSubmitListener() {
                        FreeUI_EntityCallBack<BaseResponseBean<TempRecipeEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<TempRecipeEntity>>
                                (new TypeToken<BaseResponseBean<TempRecipeEntity>>() {
                                }.getType(), getSupportFragmentManager(), this) {

                            @Override
                            public void onSuccess(Response<BaseResponseBean<TempRecipeEntity>> response) {
                                super.onSuccess(response);
                                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                                    showConfirmDialog("激活成功");
//                                    etEqpID.setText("");
//                                    etLot.setText("");
//                                    etChipName.setText("");
//                                    etDBCode.setText("");
//                                    etPackageType.setText("");
//                                    tvWrie.setText("");
//                                    etWaferSize.setText("");
//                                    etDieSize.setText("");
                                    mID = -1;
                                    mAdapter.setNewData(null);
                                    TempRecipeRequestPostNet();
                                }
                            }

                            @Override
                            public void onError(Response<BaseResponseBean<TempRecipeEntity>> response) {
                                super.onError(response);
                                loadError(response.getException(), "updateRecipeStatus");
                            }
                        };
                        JsonObject map = new JsonObject();
                        map.addProperty("id", mID);
                        map.addProperty("productionInfo", tvProcessName.getText().toString());
                        map.addProperty("status", -1);
                        map.addProperty("recipeType", mRecipeType);
                        map.addProperty("procedure", tvProcessName.getText().toString());
                        map.addProperty("WireSpec", getText(etWrieSpec));
                        map.addProperty("WaferSize", getText(etWaferSize));
                        map.addProperty("DieSize", getText(etDieSize));
                        map.addProperty("ChipName", getText(etChipName));
                        map.addProperty("DBCODE", getText(etDBCode));
                        map.addProperty("PACKAGETYPE", getText(etPackageType));
                        map.addProperty("WRIESPEC", getText(etWrieSpec));
                        map.addProperty("DieIsSingle",single);
                        map.addProperty("die1",getText(etDIE1));
                        map.addProperty("die2",getText(etDIE2));
                        map.addProperty("die3",getText(etDIE3));
                        map.addProperty("die4",getText(etDIE4));
                        map.addProperty("die5",getText(etDIE5));
                        map.addProperty("die6",getText(etDIE6));
                        map.addProperty("recipeSource",tvProgramSource.getText().toString());
                        map.addProperty("reason",getText(etUpDesc));
                        map.addProperty("curChipName",getText(etCurChipName));
                        if (!tvCHIPTHICKNESS.getText().toString().equals("")){
                            map.addProperty("maxWaferThickness",Integer.parseInt(tvCHIPTHICKNESS.getText().toString()) + 9);
                            map.addProperty("minWaferThickness",Integer.parseInt(tvCHIPTHICKNESS.getText().toString()) - 9);
                        }
                        NetUtils.requestPostNet("updateRecipeStatus", "updateRecipeStatus", TempRecipeActivity.this, map, callBack);
                    }
                });
                break;
            case R.id.tvBaseSubmit:
                TempRecipeRequestPostNet();
                break;
            case R.id.rbSingle1:
                single = "单";
                break;
            case R.id.rbSingle2:
                single = "双";
                break;
            case R.id.rbSingle3:
                single = "四";
                break;
            case R.id.rbSingle4:
                single = "六";
                break;
            case R.id.flProgramSource:
                if (mProgramSourcePop != null) {
                    if (mProgramSourcePop.isShowing()) {
                        mProgramSourcePop.dismiss();
                    }
                } else {
                    mProgramSourcePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flProgramSource.getWidth(), mProgramSourceList, ivProgramSource, (codeS, i) -> {
                        tvProgramSource.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivProgramSource);
                mProgramSourcePop.showAsDropDown(flProgramSource, 0, 0);
                break;
        }
    }

    private void TempRecipeRequestPostNet() {
        FreeUI_EntityCallBack<BaseResponseBean<TempRecipeEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<TempRecipeEntity>>
                (new TypeToken<BaseResponseBean<TempRecipeEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<TempRecipeEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    List<TempRecipeEntity.TempRecipeInfoEntity> list = response.body().getResponse().getBody().getList();
                    if (list.size() <= 0) {
                        showToast("暂无Recipe信息", false);
                        return;
                    }
//                    mID = list.get(0).getId();
                    mAdapter.setNewData(list);
                    mAdapter.setmSelectorPos(-1);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<TempRecipeEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "getRecipeByStatus");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("total", 13);
        map.addProperty("pageNo", 1);
        map.addProperty("pageSize", 50);
        map.addProperty("sort", "createTime");
        map.addProperty("order", "descending");
        map.addProperty("equipmentId", EQPID);
        map.addProperty("status", -1);
        map.addProperty("procedure", PROCESSNAME);
        NetUtils.requestPostNet("IF.getRecipeByStatus", "getRecipeByStatus", TempRecipeActivity.this, map, callBack);

    }

    private void cleanWBShow(){

        etDIE1.setText("");
        etDIE2.setText("");
        etDIE3.setText("");
        etDIE4.setText("");
        etDIE5.setText("");
        etDIE6.setText("");
        etDIE6.setText("");
        etCurChipName.setText("");
        tvProgramSource.setText("");
        etUpDesc.setText("");

    }


}
